package opensource.web.util.db;

import java.io.IOException;
import java.net.URLDecoder;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;

import opensource.web.util.configure.Configure;

public class DBM {

	static {
		try {
			Class.forName("com.mysql.jdbc.Driver");	
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	private Connection conn = null;
	private static DBM connector = new DBM();
	
	private DBM() {
		try {
			String path = this.getClass().getClassLoader().getResource("/").getPath().toString();
			path = URLDecoder.decode(path, "UTF-8");	// 消除文件夹目录中空格带来的问题(在Windows中比较常见, 如program files/)
			path = path+"conf.property";
			
			Configure configure = new Configure(path);
			HashMap<String, String> conf = configure.GetConfigure();
			
			StringBuffer url = new StringBuffer("jdbc:");
			String dbs = conf.get("Database");
			// 默认为mysql数据库
			if (dbs.length() == 0) {
				dbs = "mysql";
			}
			url.append(dbs).append("://").append(conf.get("Url")).append(":")
			   .append(conf.get("Post")).append("/").append(conf.get("DBName"));
			
			conn=DriverManager.getConnection(url.toString(), conf.get("User"), conf.get("Password"));
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static DBM getInstance() {

		synchronized (DBM.class) {
			if (connector == null) connector = new DBM();
			return connector;
		}
	}
	
	public PreparedStatement getDBInterface(String sql) throws SQLException {
		return conn.prepareStatement(sql);
	}

	public ResultSet singleQuery(String sql) throws SQLException {
		return conn.createStatement().executeQuery(sql);
	}
}
